package app.Insam.VNC;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

public final class InsamDebugger {
	public static final String TAG = "InsamApp";
	
	public static final int ACTION_SHOW_DELAY = 0xf0;

	public static long mNextUptime;	
	private static boolean mDebug;
	private static Context mAppContext;	
	private static PendingIntent mContent;
	private static NotificationManager mNotiManager;
	private static Notification mNoti;
	
	public static void init(Context _context, boolean _debugging) {
		mAppContext = _context;
		mDebug = _debugging;
		Log.d(TAG, "InsamDebugger init. Debugging is " + _debugging);
		
		Intent intent = new Intent(mAppContext, InsamService.class);
		intent.addFlags(InsamDebugger.ACTION_SHOW_DELAY);	
		mContent = PendingIntent.getService(mAppContext, 0, intent, 0);	
		
		mNotiManager = (NotificationManager)mAppContext.getSystemService(Context.NOTIFICATION_SERVICE);	
		mNoti = new Notification(R.drawable.debug, "Debugger Update", 0);
//		mNoti.flags |= Notification.DEFAULT_ALL;
//		mNoti.flags |= Notification.FLAG_AUTO_CANCEL; 
		mNoti.vibrate = new long[] {120,80,120,80};
		mNoti.number = 0;
		notify("Start! Waiting for Signal...");
	}
	
	public static void notify(String _text) {	
		if(mDebug) {
			mNoti.when = System.currentTimeMillis();
			mNoti.number++;
			mNoti.setLatestEventInfo(mAppContext, "InsamVNC Debugging", _text, mContent);
			mNotiManager.notify(InsamNotificationManager.NOTI_DEBUG, mNoti);
		}
	}
	
	public static void cancel() {
		if(mDebug) {
			mNoti.number = 0;
			mNotiManager.cancel(InsamNotificationManager.NOTI_DEBUG);
		}
	}
	
	public static void toast(String _tag, String _text) {
		if(mDebug) {
			Toast.makeText(mAppContext, _text, Toast.LENGTH_SHORT).show();
		}
		Log.d(_tag, _text);
	}
	
	public static void updateNextUptime(int _left) {
		if(mDebug) {
			mNextUptime = SystemClock.uptimeMillis() + _left;
		}
	}
	
	public static boolean isDebug() {
		return mDebug;
	}
	
	public static void set(boolean _debug) {
		Log.d(TAG, "Debugger " + _debug);
		if(_debug) {
			mDebug=true;
			InsamScheduler.compel(InsamService.ACTION_SCAN_LOCATION);
		} else {
			cancel();
			mDebug=false;			
		}
	}
	
	public static void showDelay() {
		if(mDebug) {
			mNoti.number = 0;
			toast(InsamScheduler.TAG, String.format("task %d: %dsec left\nsleep:%dsec left", InsamScheduler.mtaskId, (InsamScheduler.mWhen-SystemClock.elapsedRealtime())/1000, (mNextUptime-SystemClock.uptimeMillis())/1000));
		}
	}
}
